package com.eascs.archive.dubbo;


import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.eascs.admin.common.service.IArchiveService;
import com.eascs.admin.o2o.internal.util.StatusContexts;
import com.eascs.admin.o2o.loan.entity.O2oLoanapplyEntity;
import com.eascs.admin.o2o.loan.service.O2oLoanapplyService;
import com.eascs.app.log.Logger;
import com.eascs.app.log.LoggerFactory;
import com.eascs.archive.entity.ArchiveExportQueryVo;
import com.eascs.archive.service.ArchiveExportService;
import com.eascs.placeonfile.service.O2oFileService;
import com.eascs.workflow.common.entity.wf.ProcessTemplate;
import com.eascs.workflow.common.service.wf.WorkFlowService;
import com.eascs.workflow.common.vo.ModelResult;
import com.eascs.workflow.common.vo.WFRequestParam;

@Service
public class ArchiveTask implements IArchiveService{
	protected final Logger logger = LoggerFactory.getLogger(getClass());
	@Autowired
	O2oFileService fileService;
	@Reference
	WorkFlowService workFlowService;
	@Autowired
	private O2oLoanapplyService o2oLoanapplyService;
	@Autowired
	private ArchiveExportService archiveExportService;
	
	@Override
	public com.eascs.admin.common.vo.ModelResult<Boolean> startUpPlaceOnFile() {
		logger.info("开始自动归档");
		com.eascs.admin.common.vo.ModelResult<Boolean> modle = new com.eascs.admin.common.vo.ModelResult<>();
		try {
			SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
			Date StartDate =sdf.parse("2017-05-03");//2017/05/02后的单自动归档
			List<O2oLoanapplyEntity> loans = fileService.getLoansArchive(StartDate);
			logger.info("共[{}]条数据需要自动归档", loans.size());
			if (null != loans && loans.size() > 0) {
				for (int i = 0; i < loans.size(); i++) {
					logger.info("--第[{}]条自动归档 ，单据编号[{}],贷款id[{}]", i+1,loans.get(i).getBillCode(),loans.get(i).getLoanapplyNo());
					this.startUp(loans.get(i).getLoanapplyNo());
				}
			} else {
				logger.info("没有自动启动归档数据");
			}
		} catch (Exception e) {
			logger.error("归档流程启动失败，失败原因：{}", e);
			return modle.withError("归档流程启动失败", e.getMessage());
		}
		logger.info("结束自动归档");
		return modle.withModel(Boolean.TRUE);
	}
	
	/**
	 * @Title: startUp
	 * @Description: 自动启动归档
	 * @author 
	 * @param loanapplyNo
	 * @return
	 * @return ModelResult<Boolean>
	 * @throws
	 * @date 2017年3月16日 上午10:00:39
	 */
	public ModelResult<Boolean> startUp(String loanapplyNo) {
		try {
			O2oLoanapplyEntity loan = o2oLoanapplyService.findById(loanapplyNo);
			WFRequestParam param = new WFRequestParam();
			param.setReferId(loan.getLoanapplyNo());
			param.setReferCode(loan.getBillCode());
			param.setReferUrl("http://xxxx.eascs.com/getDetail");
			param.setSystemModule(ProcessTemplate.SYSTEM_MODULE_O2O);
			param.setProcessType(String.valueOf(ProcessTemplate.PROECESS_TYPE_ARCHIVE));
			param.setProcessVersion("v1");
			param.setAppliedby(loan.getOperatorNo());
			param.setAppliedbyName(loan.getOperatorName());
			param.setOrgNo(loan.getLtd());
			//摘要
			StringBuffer appliedDes = new StringBuffer("借款人:");
			appliedDes.append(o2oLoanapplyService.findLoanUserEntity(loan.getLoanapplyNo(),loan.getLoanId()).getUserFullName());
			appliedDes.append("，申请金额:");
			java.text.DecimalFormat df=new java.text.DecimalFormat("0.00"); //格式化，保留两位小数 
			appliedDes.append(df.format(loan.getLoanaMount().doubleValue()));
			param.setAppliedDes(appliedDes.toString());
			logger.info("启动归档，参数有贷款id：【{}】，贷款编号：【{}】，系统模块：【{}】，流程类型：【{}】，经营平台id：【{}】", loan.getLoanapplyNo(), loan.getBillCode(), ProcessTemplate.SYSTEM_MODULE_O2O, param.getProcessType(), loan.getLtd());
			ModelResult<Boolean> modelResult = workFlowService.instance(param);
			if (modelResult.isSuccess()) {
				o2oLoanapplyService.updateOnfileStatus(StatusContexts.WFTYPE_STATUS_RUN, loan.getLoanapplyNo());
			} else {
				logger.error("启动归档失败，贷款单号为：【{}】，错误信息{}", loanapplyNo, modelResult.getErrMsg());
			}
			return modelResult;
		} catch (Exception e) {
			logger.error("归档失败，贷款单号为：【{}】，错误：[{}]，", loanapplyNo, e);
			return new ModelResult<Boolean>("place on file error", "归档失败");
		}
	}

	@Override
	public com.eascs.admin.common.vo.ModelResult<Boolean> buildArchiveExport() {
		com.eascs.admin.common.vo.ModelResult<Boolean> modle = new com.eascs.admin.common.vo.ModelResult<>();
		new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					int pageSize=100;
					int pageIndex=0;
					boolean flag=true;
					while(flag){
						List<ArchiveExportQueryVo> list =archiveExportService.buildArchiveExport(pageSize, pageIndex);
						if(list == null || list.size() < pageSize)
							flag=false;
						
						pageIndex++;
					}
				} catch (Exception e) {
					logger.error("归档定时导出数据生产失败，message：{},stack：{}", e.getMessage(),e.getStackTrace());
				}
			}
		}).start();
		
		return modle.withModel(Boolean.TRUE);
	}
}
